import json
import requests


def get_repository_info(repository_id):
    from main import get_service
    service_ip, service_port = get_service("backend")
    params = {
        "repo_id": repository_id,
        "with_readme": 1
    }
    result = requests.get(f"http://{service_ip}:{service_port}/api/repo", params=params)
    if result.status_code != 200:
        raise Exception(f"服务调用异常:调用失败-{result.status_code}")
    return json.loads(result.text)["payload"]



def get_commit_info(repository_id, commit_id):
    from main import get_service
    service_ip, service_port = get_service("backend")
    params = {
        "repo_id": repository_id,
        "commit_hash": commit_id,
        "brief_only": 1
    }
    result = requests.get(f"http://{service_ip}:{service_port}/api/file", params=params)
    if result.status_code != 200:
        raise Exception(f"服务调用异常:调用失败-{result.status_code}")
    payloads = json.loads(result.text)
    commit = {"info": payloads["msg"]}
    comments = {}
    for payload in payloads["payload"]:
        if not payload["binary"]:
            if payload["comments"] is not None:
                comments[payload["path"]] = json.loads(payload["comments"])
            else:
                comments[payload["path"]] = None
    commit["comments"] = comments
    return commit
